# -*- coding: utf-8 -*-
from PyQt5.Qt import *
from libs.Scene import Scene
class BaseView(QGraphicsView):
    '''subclass of QGraphicsView'''
    def __init__(self,*args,**kwargs):
        super.__init__(*args,**kwargs)
        self.setWindowTitle("图片展示区域")
        # 两个画布
        self.pix1 = QPixmap(self.size())
        self.pix2 = QPixmap()
        self.pix1.fill(Qt.transparent)  # 添加背景颜色，否则画布默认为黑色,这里设置为透明
        # self.setPixmap(QPixmap.fromImage(QImage("icon/title.png")))
        # self.setScaledContents(True)
        # 绘制起止点坐标
        self.beginpoint = QPoint()
        self.endpoint = QPoint()

    def resizeEvent(self, evt):
        super().resizeEvent(evt)
        self.pix1 = QPixmap(self.size())
        self.pix1.fill(Qt.transparent)  # 添加背景颜色，否则画布默认为黑色

    def mousePressEvent(self, evt):
        if evt.button() == Qt.LeftButton:
            self.beginpoint = evt.pos()

    def mouseMoveEvent(self, evt):
        if Qt.LeftButton & evt.buttons():
            self.endpoint = evt.pos()
            self.update()  # 重绘必不可少，重绘调用绘制事件

    def mouseReleaseEvent(self, evt):
        self.pix1 = self.pix2.copy()  # 将画布pix2上的内容保存到pix1中

    def paintEvent(self, evt):
        super().paintEvent(evt)  # 调用父类的功能很有必要，否则会导致一些没有考虑到的方法失效
        x = self.beginpoint.x()
        y = self.beginpoint.y()
        w = self.endpoint.x() - self.beginpoint.x()
        h = self.endpoint.y() - self.beginpoint.y()

        # 将pix1画布信息copy给pix2
        self.pix2 = self.pix1.copy()
        # 创建两个画笔
        p1 = QPainter(self.pix2)
        p2 = QPainter(self)
        p1.setPen(QPen(Qt.black, 2, Qt.DotLine))  # 设置画笔格式

        p1.drawRect(x, y, w, h)
        p2.drawPixmap(0, 0, self.pix2)


if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    view = QGraphicsView()
    #view.resize(500,500)
    pixmap = QPixmap('D:\\pythonProject\\QGrphicsView框架学习\\back.jpg')
    scene = QGraphicsScene()
    view.setScene(scene)
    view.show()

    sys.exit(app.exec_())
